﻿using GenericHtml;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WLFramework.Validation;
using WLFramework.Web;
using WLFramework.DataAccess;
using WLFramework.Data.Linq;
using WLFramework.Json;

namespace SampleSite.admin.ajax.table
{
    /// <summary>
    /// add 的摘要说明
    /// </summary>
    public class add : AjaxHttpHandler
    {
        public class InputData
        {
            [Required]
            public string Key { get; set; }

            [Required]
            public string Template { get; set; }

            public string Description { get; set; }
        }

        public override void OnProcessRequest(HttpContext context)
        {
            InputData data;
            var errs = context.GetModel<InputData>(out data);
            if (errs.Count > 0)
                throw new ArgumentException("参数错误");

            using (CommandHelper db = new CommandHelper(CommandMethod.Write))
            {
                db.Context.BeginTransaction();

                data.Key = data.Key.ToLower();

                if (db.Context.dy_DynamicTables.Where(k => k.TableName == data.Key)
                      .Count() > 0)
                    throw new ArgumentException("Key已经存在");

                int id = Convert.ToInt32(db.Context.dy_DynamicTables
                                .InsertWithIdentity(() => new dy_DynamicTables
                                {
                                    TableName = data.Key,
                                    Description = data.Description,
                                    Template = data.Template,
                                    State = 0,
                                }));

                db.Context.CommitTransaction();
                context.Response.Write(JSON.Instance.ToJSON(JSONResult.Success));
            }
        }
    }
}